package com.cap.dreamcircle.View;

import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Base.BaseFragment;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Action.KeyCounterAction;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.UserInfoBean;
import com.cap.dreamcircle.Model.Bean.WechatAccessEntity;
import com.cap.dreamcircle.Model.IExternalModel;
import com.cap.dreamcircle.Model.IUserModel;
import com.cap.dreamcircle.Model.Impl.ExternalModelImpl;
import com.cap.dreamcircle.Model.Impl.UserModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DisplayUtil;
import com.cap.dreamcircle.Utils.JPushUtils;
import com.cap.dreamcircle.Utils.KeyCounterUtils;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.cap.dreamcircle.Utils.ViewUtils;
import com.caption.update.UpdateUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.bottom_imv_main)
    ImageView bottom_imv_main;
    @BindView(R.id.bottom_imv_dream_circle)
    ImageView bottom_imv_dream_circle;
    @BindView(R.id.bottom_imv_person_info)
    ImageView bottom_imv_person_info;
    @BindView(R.id.layout_bottom_tab_main)
    RelativeLayout layout_bottom_tab_main;
    @BindView(R.id.layout_bottom_tab_dream_circle)
    RelativeLayout layout_bottom_tab_dream_circle;
    @BindView(R.id.layout_bottom_tab_person_info)
    RelativeLayout layout_bottom_tab_person_info;
    @BindView(R.id.frame_layout_content)
    FrameLayout frame_layout_content;

    private TextView tv_later_bind;
    private LinearLayout layout_bind_phone;
    private LinearLayout layout_bind_wechat;

    private int page_index = 0;
    private FragmentManager mFragmentManager;
    private BaseFragment currentFragment;
    private BaseFragment mainFragment;
    private BaseFragment dreamCircleFragment;
    private BaseFragment settingFragment;

    private View notice_bind_view;
    private Dialog notice_bind_dialog;

    private IExternalModel externalModel;
    private IUserModel userModel;

    private IWXAPI api;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        bottom_imv_main.setSelected(true);
        mFragmentManager = getSupportFragmentManager();
        if (mainFragment == null) {
            mainFragment = ViewUtils.createFragment(FragmentMain.class, true);
            currentFragment = mainFragment;
            mFragmentManager.beginTransaction().add(R.id.frame_layout_content, currentFragment).commitAllowingStateLoss();
        }
        notice_bind_view = View.inflate(MainActivity.this, R.layout.dialog_bind_notice, null);
        initDialoigViews();
        initBindDialog();
        externalModel = new ExternalModelImpl();
        userModel = new UserModelImpl();
        if (PreferenceUtils.GetStartCount() % 5 == 0) {
            requestUserInfo();
        }
        api = WXAPIFactory.createWXAPI(this, Constants.WEIXIN_APPID, false);
        api.registerApp(Constants.WEIXIN_APPID);
        UpdateUtils.getInit().update(this, UpdateUtils.CHECK_AUTO);
        JPushUtils.RegisterJpush();
    }

    private void requestUserInfo() {
        userModel.RequestUserInfo().compose(TransformUtils.<UserInfoBean>defaultSchedulers()).subscribe(new Subscriber<UserInfoBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(UserInfoBean resposne) {
                if (resposne.getCode() == 0) {
                    if ("device".equals(resposne.getUserType())) {
                        notice_bind_dialog.show();
                    }
                }
            }
        });
    }

    private void initDialoigViews() {
        tv_later_bind = (TextView) notice_bind_view.findViewById(R.id.tv_later_bind);
        layout_bind_phone = (LinearLayout) notice_bind_view.findViewById(R.id.layout_bind_phone);
        layout_bind_wechat = (LinearLayout) notice_bind_view.findViewById(R.id.layout_bind_wechat);
        tv_later_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notice_bind_dialog.dismiss();
                KeyCounterAction action = new KeyCounterAction();
                action.setKey("b2e39d7fc1014ab7b5f2186b70308af3");
                EventBus.getDefault().post(action);
            }
        });
        layout_bind_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyCounterUtils.SendKeyCounter("d7ad292c502149b88ea5eb3e45d710c6");
                notice_bind_dialog.dismiss();
                Intent intent = new Intent(MainActivity.this, BindPhoneNumActivity.class);
                startActivity(intent);
            }
        });
        layout_bind_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyCounterUtils.SendKeyCounter("9b2ad489c066440ab8d39a08ac531568");

                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_login_state";
                api.sendReq(req);
            }
        });
    }

    private void doBindWechat() {
        String request_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WEIXIN_APPID + "&secret=" + Constants.WEIXIN_APPSECRET + "&code=" + Constants.WECHAT_LOGIN_CODE + "&grant_type=authorization_code";
        externalModel.getExternalRequest(request_url).flatMap(new Func1<JsonObject, Observable<WechatAccessEntity>>() {
            @Override
            public Observable<WechatAccessEntity> call(JsonObject jsonObject) {
                String json_string = jsonObject.toString();
                WechatAccessEntity access = (new Gson()).fromJson(json_string, WechatAccessEntity.class);
                return Observable.just(access);
            }
        }).flatMap(new Func1<WechatAccessEntity, Observable<BaseBean>>() {
            @Override
            public Observable<BaseBean> call(WechatAccessEntity wechatAccessEntity) {
                return userModel.BindWechat(wechatAccessEntity.getUnionid());
            }
        }).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                Constants.WECHAT_LOGIN_CODE = "";
                notice_bind_dialog.dismiss();
                hideProgress();
                ToastUtils.showShortToast(MainActivity.this, "绑定微信成功");
            }

            @Override
            public void onFailure(BaseBean response) {
                Constants.WECHAT_LOGIN_CODE = "";
                notice_bind_dialog.dismiss();
                hideProgress();
                ToastUtils.showShortToast(MainActivity.this, response.getDesc());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(Constants.WECHAT_LOGIN_CODE)) {
            showProgress();
            doBindWechat();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this).title("提示").content("是否确定退出?").positiveText("确定").negativeText("取消").cancelable(false).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    App.GetInstance().finishActivity();
                }
            }).build();
            dialog.show();
        } else {
            return super.onKeyDown(keyCode, event);
        }
        return true;
    }

    private void initBindDialog() {
        notice_bind_dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = notice_bind_dialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(MainActivity.this, 40);
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        notice_bind_dialog.setCancelable(false);
        notice_bind_dialog.setContentView(notice_bind_view);
    }

    @Override
    public void setupData() {
        layout_bottom_tab_main.setOnClickListener(this);
        layout_bottom_tab_dream_circle.setOnClickListener(this);
        layout_bottom_tab_person_info.setOnClickListener(this);
    }

    private void clearAllStates() {
        bottom_imv_main.setSelected(false);
        bottom_imv_dream_circle.setSelected(false);
        bottom_imv_person_info.setSelected(false);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.layout_bottom_tab_main:
                KeyCounterUtils.SendKeyCounter("7cdfc42f300a4787b2a5e96eb9a0a559");
                clearAllStates();
                bottom_imv_main.setSelected(true);
                if (page_index != 0) {
                    mFragmentManager.beginTransaction().hide(currentFragment).show(mainFragment).commitAllowingStateLoss();
                    page_index = 0;
                }
                break;
            case R.id.layout_bottom_tab_dream_circle:
                KeyCounterUtils.SendKeyCounter("8740023fbacc410681d311b6b87a9b73");
                clearAllStates();
                bottom_imv_dream_circle.setSelected(true);
                if (page_index != 1) {
                    if (dreamCircleFragment == null) {
                        dreamCircleFragment = ViewUtils.createFragment(FragmentDreamCircle.class, true);
                        mFragmentManager.beginTransaction().hide(currentFragment).add(R.id.frame_layout_content, dreamCircleFragment).commitAllowingStateLoss();
                    } else {
                        mFragmentManager.beginTransaction().hide(currentFragment).show(dreamCircleFragment).commitAllowingStateLoss();
                    }
                    page_index = 1;
                    currentFragment = dreamCircleFragment;
                }
                break;
            case R.id.layout_bottom_tab_person_info:
                KeyCounterUtils.SendKeyCounter("834b0f470be94f36995792f4d774f2fe");
                clearAllStates();
                bottom_imv_person_info.setSelected(true);
                if (page_index != 2) {
                    if (settingFragment == null) {
                        settingFragment = ViewUtils.createFragment(FragmentSettings.class, true);
                        mFragmentManager.beginTransaction().hide(currentFragment).add(R.id.frame_layout_content, settingFragment).commitAllowingStateLoss();
                    } else {
                        mFragmentManager.beginTransaction().hide(currentFragment).show(settingFragment).commitAllowingStateLoss();
                    }
                    page_index = 2;
                    currentFragment = settingFragment;
                }
                break;
        }
    }
}
